
var AddressBookPlugin;

var flipShown = false;
var animation = {duration:0, starttime:0, to:1.0, now:0.0, from:0.0, firstElement:null, timer:null};
var username_Global;
var password_Global;
var Islogged_Global;
var initial_transition;
var shake_timer;
var shake_count;
var shake_pad=3;
var vibration;
var delete_message;
var queue_mess;
var selectedContatcIndex = 0;
var displayedContact=0;

//Set UP the SMS Engine
var SMSEngine;

var wasEnterKeyPressedBeforSearch=false; //this is a triky variable we use it because when we hit enter on the search filed the search method is called, but we want to use the enter to select a contact. unfortunately the search method will reset the selected contact. Therefore we have to disable the search when the enter key was pressed.

// Widget preferences keys constants
var kUsernameKey = "username";
var kPasswordKey = "password";
var kSkinNameKey = "skin_name";
var kSkinXKey = "skin_x";
var kSkinYKey = "skin_y";
var kPrefFileExistsKey = "pref_file_exists";
var kVibrationKey = "vibration";
var kDeleteMessageKey = "delete_message";
var kContactSearchFilterKey = "contactSearchFilter";
var kSmsEngineKey = "smsEngine";

// Widget preferences default values
var gDefaultUsername = "";
var gDefaultPassword = "";
var gDefaultSkin_name = "default_plastic_black.png";
var gDefaultSkin_x = "151";
var gDefaultSkin_y = "99";
var gDefaultVibration = true;
var gDefaultDelete_message = false;
var gDefaultContactSearchFilter = "";
var gDefaultSmsEngine = "Sunrise";

function createKey(key) {
	if (window.widget) {
        key = widget.identifier + "-" + key;
	}
	return key;
}

function setInstanceAndGlobalPreferenceForKey(value, key) {
	setInstancePreferenceForKey(value, key);
	setGlobalPreferenceForKey(value, key);
	return value;
}

function setInstancePreferenceForKey(value, key) {
	setGlobalPreferenceForKey(value, createKey(key));
}

function setGlobalPreferenceForKey(value, key) {
	if (window.widget) {
		widget.setPreferenceForKey(value, key);
	}
}

function preferenceForKey(key) {
	var result;
	if (window.widget) {
		result = widget.preferenceForKey(createKey(key));
		if (!result) {
			result = widget.preferenceForKey(key);
		}
	}
	if (!result) {
		result = eval("gDefault" + key.substring(0,1).toUpperCase() + key.substring(1));
	}
	return result;
}

function onremove() {
	setInstancePreferenceForKey(null, kUsernameKey);
	setInstancePreferenceForKey(null, kPasswordKey);
	setInstancePreferenceForKey(null, kSkinNameKey);
	setInstancePreferenceForKey(null, kSkinXKey);
	setInstancePreferenceForKey(null, kSkinYKey);
	setInstancePreferenceForKey(null, kPrefFileExistsKey);
	setInstancePreferenceForKey(null, kVibrationKey);
	setInstancePreferenceForKey(null, kDeleteMessageKey);
	setInstancePreferenceForKey(null, kContactSearchFilterKey);
	setInstancePreferenceForKey(null, kSmsEngineKey);	
}


if (window.widget) {
	widget.onremove = onremove;
}

function shake_widget() {
	front.style.left=shake_pad + "px";
	shake_pad *= -1;
	if (shake_count == 10) {
		clearInterval(shake_timer);
		front.style.left="0px";
	} else
		shake_count++;
}

function mainTextFocusEvent(event){
	receiver_auto_complete.style.visibility="hidden";
}


function keyEvent(event){

	if(event.keyCode==13)
		wasEnterKeyPressedBeforSearch=true;
	else
		wasEnterKeyPressedBeforSearch=false;

	if(((event.type == "keydown" && event.keyCode==9) || (event.type == "keyup" && event.keyCode==13))
	    && receiver_text_area.value ==""){
		receiver_auto_complete.style.visibility="hidden";
		return focusMessage();
	}
	
	if(event.type == "keydown" && event.keyCode==40){  //down
		highlight(selectedContatcIndex+1);
	}
	
	if(event.type == "keydown" && event.keyCode==38){ //up
		highlight(selectedContatcIndex-1);
	}
	
 
	if(event.type == "keyup" && event.keyCode==13 ){ //The enter has before to be executed than I can handel it
		//searchContacs();
		firstContact = document.getElementById("contact-" + selectedContatcIndex)
		if(firstContact!=null){
			firstContactNum = firstContact.getAttribute('number');
			firstContactName = firstContact.getAttribute('name');
			selctedContact(firstContactName,firstContactNum);
		}
		event.bubbles=false;
		event.cancelBubble=true;
		event.stopPropagation();		
		focusMessage();
		return;
	}

	if(event.type == "keydown" && event.keyCode==9){  //I need to catch the Tab before the key is thrated
		//searchContacs();
		firstContact = document.getElementById("contact-" + selectedContatcIndex)
		if(firstContact!=null){
			firstContactNum = firstContact.getAttribute('number');
			firstContactName = firstContact.getAttribute('name');
			return selctedContact(firstContactName,firstContactNum);
		}
	}
}


function highlight(index){
	if(displayedContact==0) return;
	
	if(index < 0) index=displayedContact-1;
	if(index >= displayedContact) index=0;
	
	unhighlight(selectedContatcIndex);
	selectedContatcIndex=index;
	
	document.getElementById("contact-" + index).style.backgroundImage="url(images/searchBarActive.png)";
	document.getElementById("contact-link-" + index).style.color= "#FFFFFF";
}
function unhighlight(index){
	document.getElementById("contact-" + index).style.backgroundImage="url(images/searchBar.png)";
	document.getElementById("contact-link-" + index).style.color= "#333333";
}

function selctedContact(name,number){
	receiver_text_area.value=number+" ("+name +")";
	receiver_auto_complete.style.visibility="hidden";	
}

function createContactDiv (name, number,index)
{
	var enclosingDiv= document.createElement('div');
	
	enclosingDiv.setAttribute('class', 'receiver_auto_complete_text');
	enclosingDiv.setAttribute('id', 'contact-' + index);
	enclosingDiv.setAttribute('number', '' + number);
	enclosingDiv.setAttribute('name', '' + name);
	
	var html = "<A HREF=\"#\" id=\"contact-link-" + index + "\" onMouseOver=\"highlight(" + index + ");\" onMouseUP=\"selctedContact('" + name + "','"+number+"');focusMessage();\">" + name + " (" + number + ")</A>";
	
	enclosingDiv.innerHTML = html;
	
	return enclosingDiv;     
}



function searchContacs(){

	if(wasEnterKeyPressedBeforSearch)return;


	displayedContact=0;
	selectedContatcIndex = 0; //reset the current selected contact index;

	if(receiver_text_area.value ==""){
		receiver_auto_complete.style.visibility="hidden";
		return;
	}


//AddressBookPlugin.searchForStringWithBestMatch(receiver_text_area.value);
  AddressBookPlugin.searchForStringWithoutBestMatch(receiver_text_area.value);	
	
	
	receiver_auto_complete.innerHTML = "</br></br>";
	

	for (var i=0; i < AddressBookPlugin.count(); i++) {
			AddressBookPlugin.displayCardAtIndex(i);
			
			for (var j = 0; j < AddressBookPlugin.displayedItemCount(); j++)
				if(AddressBookPlugin.displayedPropertyAtIndex(j) =="Phone" &&
							(preferenceForKey(kContactSearchFilterKey) == "" ||
							 AddressBookPlugin.displayedLabelAtIndex(j) == preferenceForKey(kContactSearchFilterKey))){
					
						
					receiver_auto_complete.appendChild(createContactDiv(AddressBookPlugin.displayedName(),
																	 AddressBookPlugin.displayedValueAtIndex(j),
																	 displayedContact));
					displayedContact++;
					if(displayedContact>4)break;
				
					
				}
			if(displayedContact>4)break;
			
	}



if(displayedContact>0){
	receiver_auto_complete.style.visibility="visible";
	highlight(selectedContatcIndex);
}
else receiver_auto_complete.style.visibility="hidden";



}



function focusMessage()
{
	receiver_auto_complete.style.visibility="hidden";
	message_text_area.focus();
	
}

function get_login()
{
	username_Global = preferenceForKey(kUsernameKey);
	password_Global = preferenceForKey(kPasswordKey);

	if (username_Global && password_Global) {
		username_text_field.value = username_Global;
		password_text_field.value = password_Global;
	}
}




function set_skin(color)
{
	switch (color) {
	case "white":
		setInstanceAndGlobalPreferenceForKey("default_white.png", kSkinNameKey);
		setInstanceAndGlobalPreferenceForKey(87+105, kSkinXKey);
		setInstanceAndGlobalPreferenceForKey(57+42, kSkinYKey);
		break;
	case "dark":
		setInstanceAndGlobalPreferenceForKey("default_plastic_black.png", kSkinNameKey);
		setInstanceAndGlobalPreferenceForKey(87+64, kSkinXKey);
		setInstanceAndGlobalPreferenceForKey(57+42, kSkinYKey);
		break;
	case "black":
		setInstanceAndGlobalPreferenceForKey("default_black.png", kSkinNameKey);
		setInstanceAndGlobalPreferenceForKey(87+24, kSkinXKey);
		setInstanceAndGlobalPreferenceForKey(57+42, kSkinYKey);
		break;
	case "green":
		setInstanceAndGlobalPreferenceForKey("default_plastic_green.png", kSkinNameKey);
		setInstanceAndGlobalPreferenceForKey(87+124, kSkinXKey);
		setInstanceAndGlobalPreferenceForKey(57+2, kSkinYKey);
		break;
	case "pink":
		//widget.setPreferenceForKey("SMSuisseViola.png", "skin_name");
		setInstanceAndGlobalPreferenceForKey("default_plastic_pink.png", "skin_name");
		setInstanceAndGlobalPreferenceForKey(87+84, "skin_x");
		setInstanceAndGlobalPreferenceForKey(57+2, "skin_y");
		break;
	case "red":
		setInstanceAndGlobalPreferenceForKey("default_plastic_red.png", kSkinNameKey);
		setInstanceAndGlobalPreferenceForKey(87+44, kSkinXKey);
		setInstanceAndGlobalPreferenceForKey(57+2, kSkinYKey);
		break;
	case "blue":
		//widget.setPreferenceForKey("SMSuisseBlue.png", "skin_name");
		setInstanceAndGlobalPreferenceForKey("default_plastic_blue.png", "skin_name");
		setInstanceAndGlobalPreferenceForKey(87+4, "skin_x");
		setInstanceAndGlobalPreferenceForKey(57+2, "skin_y");
		break;
	}

	if (color=="white") {
		available_chars.style.color="#333333";
		available_sms.style.color="#333333";
	} else {
		available_chars.style.color="#FFFFFF";
		available_sms.style.color="#FFFFFF";
	}

	check.style.position = "absolute";
	check.style.left = preferenceForKey(kSkinXKey);
	check.style.top = preferenceForKey(kSkinYKey);
	front.style.backgroundImage = "url(images/skins/" + preferenceForKey(kSkinNameKey) + ")";
}

function setup()
{

     // message_text_area.innerHTML = widget.identifier; 
		
/*	
	if (!widget.preferenceForKey("pref_file_exists")) {
		widget.setPreferenceForKey(true, "pref_file_exists");
		widget.setPreferenceForKey(true, kVibrationKey);
		widget.setPreferenceForKey(false, kDeleteMessageKey);
		widget.setPreferenceForKey("151", kSkinXKey);
		widget.setPreferenceForKey("99", kSkinYKey);
		widget.setPreferenceForKey("default_plastic_black.png", kSkinNameKey);
		widget.setPreferenceForKey("", kContactSearchFilterKey);
		widget.setPreferenceForKey("Sunrise", "smsEngine");
	}
*/	

	
	vibration = preferenceForKey(kVibrationKey);
	vibration_checkbox.checked = vibration;
	
	/*
	if (!widget.preferenceForKey(kContactSearchFilterKey)) //This check is needed since we added a new preferenceKey
		widget.setPreferenceForKey("", kContactSearchFilterKey);
		
	if (!widget.preferenceForKey("smsEngine")) //This check is needed since we added a new preferenceKey
		widget.setPreferenceForKey("SunriseMail", "smsEngine");
		*/
	
	if(preferenceForKey(kContactSearchFilterKey) != ""){
		phoneBookSettingsCheckBox.checked=true;
		phoneBookSettingsField.value = preferenceForKey(kContactSearchFilterKey);
	}
			
	
	delete_message = preferenceForKey(kDeleteMessageKey);
	delete_message_checkbox.checked = delete_message;

	check.style.position = "absolute";
	check.style.left = preferenceForKey(kSkinXKey);
	check.style.top = preferenceForKey(kSkinYKey);
	front.style.backgroundImage = "url(images/skins/" + preferenceForKey(kSkinNameKey) + ")";

	var sendButton = document.getElementById("send");
	var newButton = document.getElementById("new");
	var doneButton = document.getElementById("done");

	createGenericButton(sendButton, "Send", sendNewSMS);
	createGenericButton(newButton, "New", newSMS);
	createGenericButton(doneButton, "Done", hideBack);



	get_login();
	
	if (username_Global && password_Global) {
		
		//Initialize SMS Engine
		initializeSMSEngine();
		
		available_sms.innerHTML = "Logging in...";
		setTimeout("getAvailableSMS()",50);
	} else {
		available_sms.innerHTML = "";
		sms_light.style.visibility = "hidden";
		initial_transition = setInterval("showBack(event);clearInterval(initial_transition);",3000);
	}
	

	setTimeout("checkForUpdate()",50);
	setTimeout("TrackWidget('init')",100);

	return 0;
}


function initializeSMSEngine(){
	
	
	if(preferenceForKey(kSmsEngineKey) == "SunriseMail"){
		SMSEngine = new SMSEngineSunriseMail(username_Global,password_Global);
		SMSEngine_text_field.selectedindex=0;
		SMSEngine_text_field.options[0].selected = true;
	}
		
	//if(widget.preferenceForKey("smsEngine") == "Sunrise"){
	//	SMSEngine = new SMSEngineSunrise(username_Global,password_Global);
	//	SMSEngine_text_field.selectedindex=0;
	//	SMSEngine_text_field.options[0].selected = true;
	//}
	
	if(preferenceForKey(kSmsEngineKey) == "Cablecom"){
		SMSEngine = new SMSEngineCablecom(username_Global,password_Global);
		SMSEngine_text_field.selectedindex=1;
		SMSEngine_text_field.options[1].selected = true;

	}

};


function enterflip(event)
{
    fliprollie.style.display = 'block';
}

function exitflip(event)
{
    fliprollie.style.display = 'none';
}

function limit_3 (a, b, c)
{
    return a < b ? b : (a > c ? c : a);
}

function computeNextFloat (from, to, ease)
{
    return from + (to - from) * ease;
}

function animate()
{
    var T;
    var ease;
    var time = (new Date).getTime();
    T = limit_3(time-animation.starttime, 0, animation.duration);
    if (T >= animation.duration)
    {
        clearInterval (animation.timer);
        animation.timer = null;
        animation.now = animation.to;
    }
    else
    {
        ease = 0.5 - (0.5 * Math.cos(Math.PI * T / animation.duration));
        animation.now = computeNextFloat (animation.from, animation.to, ease);
    }
    animation.firstElement.style.opacity = animation.now;
}

function mousemove (event)
{
    if (!flipShown)
    {
        if (animation.timer != null)
        {
            clearInterval (animation.timer);
            animation.timer  = null;
        }
        var starttime = (new Date).getTime() - 13;
        animation.duration = 500;
        animation.starttime = starttime;
        animation.firstElement = document.getElementById ('flip');
        animation.timer = setInterval ("animate();", 13);
        animation.from = animation.now;
        animation.to = 1.0;
        animate();
        flipShown = true;
    }
}

function mouseexit (event)
{
    if (flipShown)
    {
        // fade in the info button
        if (animation.timer != null)
        {
            clearInterval (animation.timer);
            animation.timer  = null;
        }
        var starttime = (new Date).getTime() - 13;
        animation.duration = 500;
        animation.starttime = starttime;
        animation.firstElement = document.getElementById ('flip');
        animation.timer = setInterval ("animate();", 13);
        animation.from = animation.now;
        animation.to = 0.0;
        animate();
        flipShown = false;
    }
}


function sendNewSMS()
{
	
	if (username_Global && password_Global && SMSEngine.isConnected() && SMSEngine.hasEnoughCredits(message_text_area.value.length) && receiver_text_area.value != "") {		
		sent.style.visibility="hidden";
		
		var phoneNumber =receiver_text_area.value.split(" (")[0];
		var numCheckregex = new RegExp('^[+]?[0-9./ ]+');

		if(numCheckregex.exec(phoneNumber) == null){ //The number is not valid
			error.style.visibility = "visible"; 
			return;
		}
		
		document.getElementById("send").style.visibility="hidden";
		document.getElementById("new").style.visibility="hidden";
		document.getElementById("receiver_text_area").disabled=true;
		document.getElementById("message_text_area").disabled=true;
		
		error.style.visibility="hidden";
		sending.style.visibility="visible";
		sending.src = "images/sending/sending.gif"
				
		SMSEngine.Send(message_text_area.value,phoneNumber);
		setTimeout("TrackWidget('sms')",100);
						
	} else {
		error.style.visibility = "visible";
	}
}

function engineStatusFeedBack(code){
	sms_light.style.visibility = "hidden";
	retry.style.visibility = "hidden";

	
	if (code == "Logging"){
		available_sms.innerHTML = "Logging in...";
	}
	
	if (code == "Updating"){
			available_sms.innerHTML = "Updating...";
	}
	
	if (code == "Sending"){
			available_sms.innerHTML = "Sending...";
	}

}

function needUpdateFeedBack(version){
	alert("A new version is avilable, please check our web site!");
	message_text_area.value="A new version of the SMSunrise widget is available, download it from: http://code.google.com/p/smswiss/ (click on the new button to quickly erase this message)";
}


function engineFeedBack(code)
{
	
	
	//DEBUGVERSION
	//httpResponse.responseText.execCommand("Copy");	
				
	//Hide operation progress and enable component
	sending.style.visibility="hidden";
	error.style.visibility = "hidden";
	sms_light.style.visibility = "hidden";
	retry.style.visibility = "hidden";
	document.getElementById("send").style.visibility="visible";
	document.getElementById("new").style.visibility="visible";
	document.getElementById("receiver_text_area").disabled=false;
	document.getElementById("message_text_area").disabled=false;
	
	if (code == "ConnectionError"){
		error.style.visibility = "visible";
		available_sms.innerHTML = "Conn. failed!";
		retry.style.visibility = "visible";
	}
	
	if (code == "SessionError"){
		error.style.visibility = "visible";
		available_sms.innerHTML = "Conn. failed!";
		retry.style.visibility = "visible";
	}
	
	if (code == "LogError"){
		error.style.visibility = "visible";
		available_sms.innerHTML = "Login failed!";
		retry.style.visibility = "visible";
	}
	
	if (code == "CookieError"){
		error.style.visibility = "visible";
		available_sms.innerHTML = "Cookie error!";
		retry.style.visibility = "visible";
	}

	
	if (code == "SMSCountError"){
		error.style.visibility = "visible";
		available_sms.innerHTML = "Login failed!";
		retry.style.visibility = "visible";
	}
	
	if (code == "LogOK"){
		available_sms.innerHTML = SMSEngine.getSMSCount(); //+ " SMS left";
		sms_light.style.visibility = "visible";
		sms_light.src = (!SMSEngine.isSMSCountWarning()) ? "images/greenlight.tiff" : 
						((!SMSEngine.isSMSCountCritical()) ? "images/orangelight.tiff":"images/redlight.tiff");
	}
	
	if (code == "SMSError"){
		error.style.visibility = "visible";
		available_sms.innerHTML = "SMS not sent!";
	}
	
	if (code == "SMSOK"){
		sent.style.visibility = "visible";
		available_sms.innerHTML = SMSEngine.getSMSCount();// + " SMS left";
		sms_light.style.visibility = "visible";
		sms_light.src = (!SMSEngine.isSMSCountWarning()) ? "images/greenlight.tiff" : 
						((!SMSEngine.isSMSCountCritical()) ? "images/orangelight.tiff":"images/redlight.tiff");
		if (vibration) {
			shake_count=0;
			shake_timer = setInterval("shake_widget();",40);
		}
		if (delete_message) {
			receiver_text_area.value = "";
			message_text_area.value = "";
			available_chars.innerHTML = "";
		}
	}

}

function newSMS()
{
	receiver_text_area.value = "";
	message_text_area.value = "";
	sent.style.visibility="hidden";
	error.style.visibility="hidden";
	available_chars.innerHTML = "";
}

function showBack()
{
	var front = document.getElementById("front");
	var back = document.getElementById("back");
	if (window.widget)
		widget.prepareForTransition("ToBack");
	front.style.display="none";
	back.style.display="block";
	if (window.widget)
		setTimeout ('widget.performTransition();', 0);
}

function write_login()
{
	
	if (SMSEngine_text_field.value!=""){
		setInstanceAndGlobalPreferenceForKey(SMSEngine_text_field.value, kSmsEngineKey);
	}else{
		setInstanceAndGlobalPreferenceForKey(gDefaultSmsEngine, kSmsEngineKey);
	}
		
	
	if (username_text_field.value!="" && password_text_field.value!="") {
		username_Global = setInstanceAndGlobalPreferenceForKey(document.getElementById("username_text_field").value, kUsernameKey);
		password_Global = setInstanceAndGlobalPreferenceForKey(document.getElementById("password_text_field").value, kPasswordKey);
	} else {
		username_Global = setInstanceAndGlobalPreferenceForKey("", kUsernameKey);
		password_Global = setInstanceAndGlobalPreferenceForKey("", kPasswordKey);
	}
}

function hideBack()
{
	
	if(phoneBookSettingsCheckBox.checked){
		setInstanceAndGlobalPreferenceForKey(phoneBookSettingsField.value, kContactSearchFilterKey);
	}else{
		setInstanceAndGlobalPreferenceForKey("", kContactSearchFilterKey);
	}
	
	
	if ((username_Global != username_text_field.value) 
		|| password_Global != password_text_field.value
		|| SMSEngine_text_field.value !=  preferenceForKey(kSmsEngineKey) ) {
		
		write_login();
		if (username_Global && password_Global) {
			initializeSMSEngine();
			available_sms.innerHTML = "Logging in...";
			getAvailableSMS(); //To login we use this method
		} else {
			available_sms.innerHTML = "";
			sms_light.style.visibility = "hidden";
			sending.style.visibility="hidden";
		}
	}

	var front = document.getElementById("front");
	var back = document.getElementById("back");
	if (window.widget)
		widget.prepareForTransition("ToFront");
	back.style.display="none";
	front.style.display="block";
	if (window.widget)
		setTimeout ('widget.performTransition();', 0);
	exitflip(event);
}

function getAvailableSMS(){
	sending.style.visibility="visible";
	sending.src = "images/sending/sending.gif"
	sms_light.style.visibility = "hidden";
	SMSEngine.getAvailSMS();
}



function countChars(event)
{
	
	if (message_text_area.value=="") {
		available_chars.innerHTML="";
		return;
	}

	//((... | 0) is like casting to integer
	available_chars.innerHTML = ((message_text_area.value.length-1)/SMSEngine.GetSMSCharsCount() | 0)+1 + " - " + message_text_area.value.length;
}


